from base.web import SHandler, get_files, BaseHandler
domin = 'http://pengjinyl.cn/'

'''
    1.创建商品
    2.编辑商品
    3.查询商品
    4.删除商品
    5.商品详情
'''


class create_product(SHandler):
    def post(self):
        filter = ['name', 'shortname', 'price', 'contentid', 'remark', 'level', 'pricesing']
        params = []  #字段容器
        for key in filter:
            value = self.get_argument(key, '')
            if key != 'contentid':
                value = '\'' + value + '\''
            params.append(value)
        if self.request.files:
            filesList = get_files(self.request.files)
            params.append('\'' + get_files(self.request.files) + '\'')
            filter.append('img')
        insert_data = dict(
            keys = ','.join(filter),
            values = ','.join(params)
        )
        if self.insert_sql(['insert into hs_product({keys}) values({values})'.format(**insert_data)]):
            res = self.res_success('insert')
        else:
            res = self.res_error('insert')
        self.write(res)

class modify_product(SHandler):
    def post(self):
        updateList = ['name', 'shortname', 'contentid', 'price', 'remark', 'level', 'pricesing']
        params = []
        for key in updateList:
            value = self.get_argument(key, '')
            if value:
                if key != 'contentid':
                    value = key + '=' + '\'' + value + '\''
                else:
                    value = key + '=' + value
                params.append(value)
        if self.request.files:
            params.append('img=' + '\'' + get_files(self.request.files) + '\'')
        condition = dict(
            params = ','.join(params),
            id = int(self.get_argument('id', ''))
        )
        if self.modify_sql(['update hs_product set {params} where id = {id}'.format(**condition)]):
            res = self.res_success('modify')
        else:
            res = self.res_error('modify')
        self.write(res)

class query_product(BaseHandler):
    def post(self):
        current_page = int(self.get_argument('current_page', 1))
        page_size = int(self.get_argument('page_size', 10000))
        contentid = self.get_argument('contentid', 0) or 0
        if contentid == '0':
            contentid = int(contentid)
        name = self.get_argument('name', '')
        try:
            intname = int(name)
        except:
            intname = 0
        condition = dict(
            start = (current_page - 1) * page_size,
            num = page_size,
            name = name,
            intname = intname,
            q = ('in' if contentid else 'not in'),
            contentid = contentid
        )
        total = self.query_sql('''select count(*) as total from hs_product where 
                ((name like \'%{name}%\' or shortname like \'%{name}%\' or id = {intname}))
                and (isdel = 0 and contentid {q} ({contentid}) and isdel = 0)'''.format(**condition))[0]['total']
        try:
            data = self.query_sql('''select * from hs_product where 
                ((name like \'%{name}%\' or shortname like \'%{name}%\' or id = {intname}))
                and (isdel = 0 and contentid {q} ({contentid}) and isdel = 0)  order by -level limit {start}, {num};
                '''.format(**condition))
            for i in data:
                i['ctime'] = str(i['ctime'])
            res = self.res_success('query', data, dict(total = total, domin = domin))
        except:
            res = self.res_error('query')
        self.write(res)

class del_product(SHandler):
    def post(self):
        condition = dict(
            id = int(self.get_argument('id', 0))
        )
        if self.modify_sql(['delete from hs_product where id = {id};'.format(**condition)]):
            res = self.res_success('modify')
        else:
            res = self.res_error('modify')
        self.write(res)
# class set_recommend(SHandler):
#     def post(self):
#         if self.modify_sql('update pj_product set isrecommend = {isrecommend} where id = {id};'.format(
#                 isrecommend = int(self.get_argument('isrecommend', 0)),
#                 id = int(self.get_argument('id', 0))
#             )):
#             res = self.res_success('modify')
#         else:
#             res = self.res_error('modify')
#         self.write(res)

class product_detail(SHandler):
    def post(self):
        try:
            product = self.query_sql('select * from hs_product where id = {id}'.format(id = int(self.get_argument('id', ''))))[0]
            product['ctime'] = str(product['ctime'])
            res = self.res_success('query', object={'product': product, 'domin': domin})
        except:
            res = self.res_error('query')
        self.write(res)
product_url = [
    (r'/api/product/create_product', create_product),
    (r'/api/product/modify_product', modify_product),
    (r'/api/product/query_product', query_product),
    (r'/api/product/del_product', del_product),
    # (r'/api/product/set_recommend', set_recommend),
    (r'/api/product/product_detail', product_detail)
]